<?php
// 显示所有错误
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 加载数据库配置
require_once __DIR__ . '/../config/database.php';

$message = '';
$success = true;

try {
    // 创建PDO连接
    $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET;
    $pdo = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $message .= "<div class='alert alert-success'>数据库连接成功！</div>";
    
    // 创建用户表
    $pdo->exec("CREATE TABLE IF NOT EXISTS `".DB_PREFIX."users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(50) NOT NULL,
      `password` varchar(255) NOT NULL,
      `email` varchar(100) NOT NULL,
      `nickname` varchar(50) DEFAULT NULL,
      `avatar` varchar(255) DEFAULT NULL,
      `role` enum('user','admin') NOT NULL DEFAULT 'user',
      `status` enum('active','inactive') NOT NULL DEFAULT 'active',
      `created_at` datetime NOT NULL,
      `updated_at` datetime NOT NULL,
      `last_login` datetime DEFAULT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `username` (`username`),
      UNIQUE KEY `email` (`email`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    
    $message .= "<div class='alert alert-success'>用户表创建成功！</div>";
    
    // 创建游戏表
    $pdo->exec("CREATE TABLE IF NOT EXISTS `".DB_PREFIX."games` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(100) NOT NULL,
      `description` text,
      `rules` text,
      `category` varchar(50) NOT NULL,
      `difficulty` int(11) NOT NULL DEFAULT '1',
      `status` enum('active','inactive') NOT NULL DEFAULT 'active',
      `min_age` int(11) DEFAULT '0',
      `max_age` int(11) DEFAULT '0',
      `play_time` int(11) DEFAULT '0',
      `instructions` text,
      `image` varchar(255) DEFAULT NULL,
      `created_at` datetime NOT NULL,
      `updated_at` datetime NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    
    $message .= "<div class='alert alert-success'>游戏表创建成功！</div>";
    
    // 创建成就表
    $pdo->exec("CREATE TABLE IF NOT EXISTS `".DB_PREFIX."achievements` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(100) NOT NULL,
      `description` text,
      `game_id` int(11) DEFAULT NULL,
      `criteria` varchar(255) NOT NULL,
      `points` int(11) NOT NULL DEFAULT '0',
      `icon` varchar(255) DEFAULT NULL,
      `status` enum('active','inactive') NOT NULL DEFAULT 'active',
      `created_at` datetime NOT NULL,
      `updated_at` datetime NOT NULL,
      PRIMARY KEY (`id`),
      KEY `game_id` (`game_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    
    $message .= "<div class='alert alert-success'>成就表创建成功！</div>";
    
    // 创建游戏记录表
    $pdo->exec("CREATE TABLE IF NOT EXISTS `".DB_PREFIX."game_records` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `user_id` int(11) NOT NULL,
      `game_id` int(11) NOT NULL,
      `score` int(11) NOT NULL DEFAULT '0',
      `duration` int(11) DEFAULT NULL,
      `played_at` datetime NOT NULL,
      PRIMARY KEY (`id`),
      KEY `user_id` (`user_id`),
      KEY `game_id` (`game_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    
    $message .= "<div class='alert alert-success'>游戏记录表创建成功！</div>";
    
    // 创建用户成就表
    $pdo->exec("CREATE TABLE IF NOT EXISTS `".DB_PREFIX."user_achievements` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `user_id` int(11) NOT NULL,
      `achievement_id` int(11) NOT NULL,
      `game_id` int(11) DEFAULT NULL,
      `unlocked_at` datetime NOT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `user_achievement` (`user_id`,`achievement_id`),
      KEY `achievement_id` (`achievement_id`),
      KEY `game_id` (`game_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    
    $message .= "<div class='alert alert-success'>用户成就表创建成功！</div>";
    
    // 创建系统设置表
    $pdo->exec("CREATE TABLE IF NOT EXISTS `".DB_PREFIX."settings` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `setting_key` varchar(50) NOT NULL,
      `setting_value` text,
      `type` varchar(20) NOT NULL DEFAULT 'text',
      `display_name` varchar(100) NOT NULL,
      `description` text,
      `category` varchar(50) NOT NULL DEFAULT 'general',
      `is_required` tinyint(1) NOT NULL DEFAULT '0',
      `options` text,
      PRIMARY KEY (`id`),
      UNIQUE KEY `setting_key` (`setting_key`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    
    $message .= "<div class='alert alert-success'>系统设置表创建成功！</div>";
    
    // 初始化一些系统设置
    $settingsData = [
        ['site_name', 'KidsMind 儿童思维训练平台', 'text', '网站名称', '显示在网站标题和页面中的名称', 'website', 1, ''],
        ['site_description', '专为3-8岁儿童设计的思维训练平台', 'textarea', '网站描述', '简短的网站介绍，用于SEO', 'website', 1, ''],
        ['admin_email', 'admin@example.com', 'email', '管理员邮箱', '系统通知发送到此邮箱', 'mail', 1, ''],
        ['registration_open', '1', 'boolean', '开放注册', '是否允许新用户注册', 'user', 0, ''],
        ['default_user_role', 'user', 'select', '默认用户角色', '新用户注册默认角色', 'user', 1, '{"user":"普通用户","premium":"高级用户"}'],
        ['max_login_attempts', '5', 'number', '最大登录尝试次数', '达到此次数后账户将被临时锁定', 'security', 0, ''],
        ['maintenance_mode', '0', 'boolean', '维护模式', '启用后网站将显示维护页面', 'general', 0, '']
    ];
    
    $stmt = $pdo->prepare("INSERT IGNORE INTO `".DB_PREFIX."settings` (setting_key, setting_value, type, display_name, description, category, is_required, options) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    
    foreach ($settingsData as $setting) {
        $stmt->execute($setting);
    }
    
    $message .= "<div class='alert alert-success'>系统设置初始化成功！</div>";
    
    // 检查管理员账户
    $adminCount = $pdo->query("SELECT COUNT(*) FROM `".DB_PREFIX."users` WHERE role = 'admin'")->fetchColumn();
    
    if ($adminCount == 0) {
        // 创建管理员账户
        $admin_username = 'admin';
        $admin_password = 'admin123';
        $admin_email = 'admin@example.com';
        $password_hash = password_hash($admin_password, PASSWORD_DEFAULT);
        
        $stmt = $pdo->prepare("INSERT INTO `".DB_PREFIX."users` (username, password, email, role, status, created_at, updated_at) VALUES (?, ?, ?, 'admin', 'active', NOW(), NOW())");
        $stmt->execute([$admin_username, $password_hash, $admin_email]);
        
        $message .= "<div class='alert alert-warning'>
            <strong>已创建默认管理员账户:</strong><br>
            用户名: {$admin_username}<br>
            密码: {$admin_password}<br>
            请立即登录并修改此默认密码!
        </div>";
    } else {
        $message .= "<div class='alert alert-info'>已存在管理员账户，无需创建。</div>";
    }
    
    // 添加示例游戏数据
    $gamesCount = $pdo->query("SELECT COUNT(*) FROM `".DB_PREFIX."games`")->fetchColumn();
    
    if ($gamesCount == 0) {
        $gamesData = [
            ['记忆卡牌', '通过翻转卡牌找到配对的图案，训练记忆力和注意力', '1. 点击卡牌翻转\n2. 找到两张相同的卡牌\n3. 在最短时间内完成所有配对', '记忆力训练', 1, 'active', 3, 5, 180, '使用鼠标点击卡牌进行翻转', 'uploads/games/memory_cards.jpg', date('Y-m-d H:i:s'), date('Y-m-d H:i:s')],
            ['数字排序', '将随机排列的数字按顺序排列，训练逻辑思维能力', '1. 点击数字进行移动\n2. 将所有数字按从小到大排列\n3. 在最短时间内完成任务', '逻辑思维', 2, 'active', 5, 7, 240, '使用鼠标拖拽数字调整位置', 'uploads/games/number_sort.jpg', date('Y-m-d H:i:s'), date('Y-m-d H:i:s')],
            ['形状配对', '将形状拖拽到对应的轮廓中，训练空间感知能力', '1. 拖拽形状到对应的轮廓中\n2. 所有形状都放置正确即完成\n3. 在最短时间内完成任务', '空间感知', 1, 'active', 3, 6, 150, '使用鼠标拖拽形状到对应位置', 'uploads/games/shape_match.jpg', date('Y-m-d H:i:s'), date('Y-m-d H:i:s')],
            ['动物连线', '将动物与其栖息地连接起来，训练知识和认知能力', '1. 点击动物然后点击对应的栖息地\n2. 连接所有正确的配对\n3. 错误连接会减少得分', '知识认知', 1, 'active', 4, 7, 180, '先点击左侧动物，再点击右侧栖息地', 'uploads/games/animal_match.jpg', date('Y-m-d H:i:s'), date('Y-m-d H:i:s')],
            ['简单加法', '解决基础加法题目，训练数学能力', '1. 看到加法题目\n2. 在规定时间内输入正确答案\n3. 答对得分，答错不得分', '数学能力', 2, 'active', 5, 8, 300, '使用键盘输入答案，按回车键确认', 'uploads/games/simple_addition.jpg', date('Y-m-d H:i:s'), date('Y-m-d H:i:s')]
        ];
        
        $stmt = $pdo->prepare("INSERT INTO `".DB_PREFIX."games` (name, description, rules, category, difficulty, status, min_age, max_age, play_time, instructions, image, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        foreach ($gamesData as $game) {
            $stmt->execute($game);
        }
        
        $message .= "<div class='alert alert-success'>已添加示例游戏数据！</div>";
    } else {
        $message .= "<div class='alert alert-info'>已存在游戏数据，无需添加示例。</div>";
    }
    
    // 添加示例成就数据
    $achievementsCount = $pdo->query("SELECT COUNT(*) FROM `".DB_PREFIX."achievements`")->fetchColumn();
    
    if ($achievementsCount == 0) {
        // 获取游戏ID
        $games = $pdo->query("SELECT id, name FROM `".DB_PREFIX."games` LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);
        $gameIds = [];
        
        foreach ($games as $game) {
            $gameIds[$game['name']] = $game['id'];
        }
        
        $achievementsData = [
            ['记忆大师', '在记忆卡牌游戏中获得满分', $gameIds['记忆卡牌'] ?? null, '在记忆卡牌游戏中获得100分', 50, 'uploads/achievements/memory_master.png', 'active', date('Y-m-d H:i:s'), date('Y-m-d H:i:s')],
            ['数学能手', '在简单加法游戏中连续答对10题', $gameIds['简单加法'] ?? null, '在简单加法游戏中连续答对10题', 30, 'uploads/achievements/math_expert.png', 'active', date('Y-m-d H:i:s'), date('Y-m-d H:i:s')],
            ['形状专家', '在形状配对游戏中完成所有关卡', $gameIds['形状配对'] ?? null, '完成所有形状配对关卡', 40, 'uploads/achievements/shape_expert.png', 'active', date('Y-m-d H:i:s'), date('Y-m-d H:i:s')],
            ['动物学家', '在动物连线游戏中正确连接所有动物', $gameIds['动物连线'] ?? null, '在动物连线游戏中获得满分', 35, 'uploads/achievements/animal_expert.png', 'active', date('Y-m-d H:i:s'), date('Y-m-d H:i:s')],
            ['逻辑思考者', '在数字排序游戏中用最少步骤完成', $gameIds['数字排序'] ?? null, '在数字排序游戏中少于15步完成', 45, 'uploads/achievements/logic_thinker.png', 'active', date('Y-m-d H:i:s'), date('Y-m-d H:i:s')],
            ['学习爱好者', '玩过所有类型的游戏', null, '每种类型的游戏至少玩过一次', 60, 'uploads/achievements/learning_lover.png', 'active', date('Y-m-d H:i:s'), date('Y-m-d H:i:s')],
            ['坚持不懈', '连续7天登录并玩游戏', null, '连续7天每天至少玩一次游戏', 70, 'uploads/achievements/persistent.png', 'active', date('Y-m-d H:i:s'), date('Y-m-d H:i:s')]
        ];
        
        $stmt = $pdo->prepare("INSERT INTO `".DB_PREFIX."achievements` (name, description, game_id, criteria, points, icon, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        foreach ($achievementsData as $achievement) {
            $stmt->execute($achievement);
        }
        
        $message .= "<div class='alert alert-success'>已添加示例成就数据！</div>";
    } else {
        $message .= "<div class='alert alert-info'>已存在成就数据，无需添加示例。</div>";
    }
    
    // 外键约束
    try {
        // 用户成就表外键
        $pdo->exec("ALTER TABLE `".DB_PREFIX."user_achievements` 
            ADD CONSTRAINT `".DB_PREFIX."user_achievements_user_id_fk` 
            FOREIGN KEY (`user_id`) REFERENCES `".DB_PREFIX."users` (`id`) ON DELETE CASCADE");
        
        $pdo->exec("ALTER TABLE `".DB_PREFIX."user_achievements` 
            ADD CONSTRAINT `".DB_PREFIX."user_achievements_achievement_id_fk` 
            FOREIGN KEY (`achievement_id`) REFERENCES `".DB_PREFIX."achievements` (`id`) ON DELETE CASCADE");
        
        $pdo->exec("ALTER TABLE `".DB_PREFIX."user_achievements` 
            ADD CONSTRAINT `".DB_PREFIX."user_achievements_game_id_fk` 
            FOREIGN KEY (`game_id`) REFERENCES `".DB_PREFIX."games` (`id`) ON DELETE SET NULL");
        
        // 游戏记录表外键
        $pdo->exec("ALTER TABLE `".DB_PREFIX."game_records` 
            ADD CONSTRAINT `".DB_PREFIX."game_records_user_id_fk` 
            FOREIGN KEY (`user_id`) REFERENCES `".DB_PREFIX."users` (`id`) ON DELETE CASCADE");
        
        $pdo->exec("ALTER TABLE `".DB_PREFIX."game_records` 
            ADD CONSTRAINT `".DB_PREFIX."game_records_game_id_fk` 
            FOREIGN KEY (`game_id`) REFERENCES `".DB_PREFIX."games` (`id`) ON DELETE CASCADE");
        
        // 成就表外键
        $pdo->exec("ALTER TABLE `".DB_PREFIX."achievements` 
            ADD CONSTRAINT `".DB_PREFIX."achievements_game_id_fk` 
            FOREIGN KEY (`game_id`) REFERENCES `".DB_PREFIX."games` (`id`) ON DELETE SET NULL");
        
        $message .= "<div class='alert alert-success'>外键约束创建成功！</div>";
    } catch (PDOException $e) {
        // 外键可能已存在，忽略错误
        $message .= "<div class='alert alert-warning'>外键约束创建失败或已存在：" . $e->getMessage() . "</div>";
    }
    
    $message .= "<div class='alert alert-success'><strong>所有数据表创建成功！</strong> 现在您可以<a href='login.php' class='alert-link'>登录管理后台</a>了。</div>";
    
} catch (PDOException $e) {
    $success = false;
    $message .= "<div class='alert alert-danger'><strong>错误：</strong> " . $e->getMessage() . "</div>";
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KidsMind - 数据表设置</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card shadow">
                    <div class="card-header bg-primary text-white">
                        <h4 class="mb-0">KidsMind 系统数据表设置</h4>
                    </div>
                    <div class="card-body">
                        <h5 class="card-title mb-4">数据表创建结果</h5>
                        
                        <?php echo $message; ?>
                        
                        <div class="mt-4">
                            <?php if ($success): ?>
                                <a href="index.php" class="btn btn-primary">进入管理后台</a>
                            <?php else: ?>
                                <a href="setup_tables.php" class="btn btn-warning">重试</a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html> 